//
//  MYComposeCollectionView.swift
//  NewMicroblog
//
//  Created by apple on 2016/11/1.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

private let viewCellIdentifier = "HMComposePictureViewCellIdentifier"

class MYComposeCollectionView: UICollectionView {
    ///图片数组
    lazy var images: [UIImage] = [UIImage]()
    ///执行图片浏览器的闭包
    var callBack:(()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK:- 搭建主界面
    private func setupUI(){
       // backgroundColor = UIColor.red
        isHidden = true
        register(MYComposeCollectionCell.self, forCellWithReuseIdentifier: viewCellIdentifier)
        dataSource = self
        delegate = self
    }
    ///添加选中的图片
    func addImage(image: UIImage){
        if self.images.count >= 9 {
            return
        }
        isHidden = false
        images.append(image)
        reloadData()
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let margin: CGFloat = 5
        let itemW = (width - 2 * margin) / 3
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemW, height: itemW)
        flowLayout.minimumInteritemSpacing = margin
        flowLayout.minimumLineSpacing = margin
    }

}
extension MYComposeCollectionView: UICollectionViewDataSource,UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if self.images.count == 0 || self.images.count == 9 {
            return self.images.count
        }else{
            return self.images.count + 1
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: viewCellIdentifier, for: indexPath) as! MYComposeCollectionCell
        if indexPath.item == self.images.count {
            cell.image = nil
        }else{
          cell.image = self.images[indexPath.item]
            cell.callBack = { [weak self](index: Int) in
                self?.images.remove(at: index)
                if self?.images.count == 0 {
                    self?.isHidden = true
                }

            }
            cell.indexPath = indexPath
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == self.images.count {
            callBack?()
        }
    }
}

/// 自定义cell
class MYComposeCollectionCell: UICollectionViewCell {
    ///设置当前的indexPath
    var indexPath: IndexPath?
    ///需要删除按钮所执行的闭包
    var callBack:((Int)->())?
    
    fileprivate lazy var imgeV: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    var image: UIImage?{
        didSet{
            if image == nil {
              imgeV.image = UIImage(named: "compose_pic_add")
                deleteBtn.isHidden = true
            }else{
                deleteBtn.isHidden = false
               imgeV.image = image
            }
        }
    }
    ///添加删除按钮
    private lazy var deleteBtn: UIButton = {
      let btn = UIButton()
        btn.addTarget(self, action: #selector(deleteBtnClick), for: .touchUpInside)
        btn.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 搭建主界面
    private func setupUI(){
        contentView.addSubview(imgeV)
        contentView.addSubview(deleteBtn)
        imgeV.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        deleteBtn.snp_makeConstraints { (make) in
            make.top.equalTo(imgeV)
            make.right.equalTo(imgeV)
        }
        
    }
    @objc private func deleteBtnClick(){
        if let idx = indexPath {
            callBack?(idx.item)
        }
    }

    
}
